package com.cy.cy2025.activity

import android.Manifest
import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.MotionEvent
import androidx.activity.enableEdgeToEdge
import androidx.annotation.RequiresPermission
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.AspectRatio
import androidx.camera.core.CameraProvider
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.video.FallbackStrategy
import androidx.camera.video.FileOutputOptions
import androidx.camera.video.Quality
import androidx.camera.video.QualitySelector
import androidx.camera.video.Recorder
import androidx.camera.video.Recording
import androidx.camera.video.VideoCapture
import androidx.camera.video.VideoRecordEvent
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.bumptech.glide.Glide
import com.cy.cy2025.R
import com.cy.cy2025.activity.CameraTestActivity
import com.cy.cy2025.databinding.ActivityCameraxTestBinding
import com.cy.cy2025.util.LogUtil
import com.cy.cy2025.util.PermissionUtil
import com.cy.cy2025.util.PermissionsCallback
import com.cy.cy2025.util.ToastUtil
import java.io.File

class CameraxTestActivity : AppCompatActivity() {


    // 预览配置对象
    val preview: Preview by lazy {
        Preview.Builder()
            .setTargetAspectRatio(AspectRatio.RATIO_16_9) // 设置预览比例
            .build()
            .also { it.setSurfaceProvider(binding.pv.surfaceProvider) }
    }

    //拍照配置对象
    val imageCapture: ImageCapture by lazy {
        ImageCapture.Builder()
            .setCaptureMode(ImageCapture.CAPTURE_MODE_MAXIMIZE_QUALITY)
            .setTargetRotation(binding.pv.display.rotation)
            .build()
    }


    // 配置视频录制器（Recorder）
    val recorder by lazy {
        Recorder.Builder()
            .setQualitySelector(
                QualitySelector.from(
                    Quality.HIGHEST, // 优先最高质量
                    FallbackStrategy.lowerQualityOrHigherThan(Quality.SD) // 降级策略
                )
            )
            .build()
    }

    //视频录制配置对象
    val videoCapture: VideoCapture<Recorder> by lazy {
        VideoCapture.withOutput(recorder)

    }

    var started = false

    var cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA

    // 相机提供者，用于控制相机开启和关闭等操作
    val cameraProvider: ProcessCameraProvider? by lazy {
        ProcessCameraProvider.getInstance(this@CameraxTestActivity).get()
    }

    val binding by lazy { ActivityCameraxTestBinding.inflate(layoutInflater) }

    @SuppressLint("RestrictedApi", "ClickableViewAccessibility")
    @RequiresPermission(Manifest.permission.RECORD_AUDIO)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)


        binding.btnStart.setOnClickListener {
            if (!started) {
                PermissionUtil.requestPermissions(
                    object : PermissionsCallback {
                        override fun onSuccess() {
                            bindPreview()
                            started = true
                        }

                        override fun onFailure(
                            failures: List<String>,
                            forbiddings: List<String>
                        ) {
                            ToastUtil.showShort("权限获取失败")
                        }
                    },
                    android.Manifest.permission.CAMERA,
                    android.Manifest.permission.RECORD_AUDIO,
                    android.Manifest.permission.FOREGROUND_SERVICE_MICROPHONE
                )
            }
        }


        // 拍照按钮点击事件
        binding.btnGet.setOnClickListener {

            val photoFile = File(
                getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.path + "/${System.currentTimeMillis()}.jpg"
            )
            val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()
            if (CameraSelector.DEFAULT_FRONT_CAMERA == cameraSelector) {
                runCatching {
                    outputOptions.metadata.apply {
                        isReversedHorizontal = true
                    }
                }
            }

            // 执行拍照
            imageCapture.takePicture(
                outputOptions,
                ContextCompat.getMainExecutor(this),
                object : ImageCapture.OnImageSavedCallback {
                    override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                        ToastUtil.showShort("照片保存成功：${photoFile.path}")
                        Glide.with(this@CameraxTestActivity).load(photoFile).into(binding.imageView)
                    }

                    override fun onError(exception: ImageCaptureException) {
                        ToastUtil.showShort("拍照失败$exception")
                    }
                }
            )
        }


        // 切换摄像头按钮点击事件
        binding.btnSwitch.setOnClickListener {
            switchCamera()
        }

        // 录制视频按钮点击事件

        binding.tvRecord.setOnTouchListener  { _, event ->

            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    LogUtil.d("录制视频","开始录制")
                    startRecord()
                }
                MotionEvent.ACTION_UP -> {
                    LogUtil.d("录制视频","停止录制")
                    stopRecord()
                }
            }
            true
        }


    }


    var recording: Recording? = null


    @RequiresPermission(Manifest.permission.RECORD_AUDIO)
    private fun startRecord() {
        val videoFile = File(
            getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.path + "/${System.currentTimeMillis()}.mp4"
        )
        recording = videoCapture
            .output
            .prepareRecording(this, FileOutputOptions.Builder(videoFile).build())
            .withAudioEnabled()
            .start(ContextCompat.getMainExecutor(this)) { recordEvent ->
                when (recordEvent) {
                    is VideoRecordEvent.Start -> {
                        ToastUtil.showShort("开始录制")
                    }

                    is VideoRecordEvent.Finalize -> {
                        if (recordEvent.hasError()) {
                            ToastUtil.showShort("录制失败:${recordEvent.error}")
                        } else {
                            ToastUtil.showShort("视频保存成功：${videoFile.path}")
                        }
                    }
                }
            }
    }

    private fun stopRecord() {
        if (recording != null) {
            recording?.stop()
        }
    }


    // 绑定预览视图,开启预览
    private fun bindPreview() {


        cameraProvider?.bindToLifecycle(this, cameraSelector, preview, imageCapture, videoCapture)
    }


    private fun switchCamera() {
        cameraSelector = if (CameraSelector.DEFAULT_BACK_CAMERA == cameraSelector) {
            CameraSelector.DEFAULT_FRONT_CAMERA
        } else {
            CameraSelector.DEFAULT_BACK_CAMERA
        }
        cameraProvider?.unbindAll()
        bindPreview()
    }


}